import config from "@/config"
import {
	getToken
} from '@/utils/auth'
const baseUrl = config.baseUrl;
/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
	uni.showToast({
		icon: 'none',
		title: content
	})
}
// 上传图片相关
export function upLoadFile(event, fileList) {
	// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event.file)
	let fileListLen = fileList.length
	lists.map((item) => {
		fileList.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	for (let i = 0; i < lists.length; i++) {
		console.log(lists[i].url, 'lists[i].url')
		uploadFilePromise(lists[i].url).then(res => {
			const result = res.url
			let item = fileList[fileListLen]
			fileList.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result
			}))
			fileListLen++
		})
	}

	function uploadFilePromise(url) {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				header: {
					Authorization: "Bearer " + getToken(),
				},
				url: baseUrl + '/common/upload',
				filePath: url,
				name: 'file',
				success: (res) => {
					setTimeout(() => {
						resolve(JSON.parse(res.data))
					}, 1000)
				}
			});
		})
	}
}
/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '提示',
			content: content,
			cancelText: '取消',
			confirmText: '确定',
			success: function(res) {
				resolve(res)
			}
		})
	})
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}
export function getLastPartAfterLastComma(str) {
	if (!str || str.trim() === "") {
		return ""
	} else {
		const lastCommaIndex = str.lastIndexOf(',');

		// 如果没有逗号，返回整个字符串
		if (lastCommaIndex === -1) {
			return str;
		}

		// 提取最后一个逗号之后的部分
		const lastPart = str.substring(lastCommaIndex + 1);

		return lastPart;
	}

}

//获取当前时间点
export function getNowTime() {
	const now = new Date();

	// 提取时间组件并补零
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');

	// 组合成中文格式
	return `${year}-${month}-${day} ${hours}:${minutes}`;
}

export function calculateScores(arr) {
	return arr.map(item => {
		// 确定目标ID集合
		const targetIds = item.selSingle !== undefined ? [item.selSingle] :
			Array.isArray(item.selChecked) ? item.selChecked : [];

		// 计算匹配score总和
		return item.appraisalAnswers?.reduce((sum, aweItem) => {
			if (targetIds.includes(aweItem.id)) {
				return sum + aweItem.score;
			}
			return sum;
		}, 0);
	});
}
export function calculateTotal(arr) {
	// const scores = calculateScores(arr);
	// return scores.reduce((sum, current) => sum + current, 0);
	let sum = 0;
	arr.forEach(num => {
		sum += num;
	});
	return sum
}
export function extractFilteredObjects(arr, fields = []) {
	return arr.flatMap(item => {
		const targetIds = item.selSingle !== undefined ? [item.selSingle] :
			Array.isArray(item.selChecked) ? item.selChecked : [];
		return targetIds.flatMap(id =>
			item.appraisalAnswers
			.filter(aweItem => aweItem.id === id)
			.map(aweItem =>
				fields.length > 0 ?
				Object.fromEntries(
					fields.map(field => {
						// 特殊处理 id 字段重命名
						if (field === 'id') {
							return ['appraisalAnswerId', aweItem[field]];
						}
						return [field, aweItem[field]];
					})
				) : {
					appraisalAnswerId: aweItem.id,
					...aweItem
				} // 默认包含重命名字段
			)
		);
	})
}
export function filterFields(arr, fields) {
	return arr.map(obj =>
		Object.fromEntries(
			fields.map(field => [field, obj[field]])
		)
	);
}
export function calculateScore(item) {
	const targetIds = item.selSingle !== undefined ? [item.selSingle] :
		Array.isArray(item.selChecked) ? item.selChecked : [];

	// 计算匹配score总和
	return item.appraisalAnswers?.reduce((sum, aweItem) => {
		if (targetIds.includes(aweItem.id)) {
			return sum + aweItem.score;
		}
		return sum;
	}, 0);
}
export function buildFullImageUrl(relativePath) {
	const serverUrl = config.baseUrlImage;
	// 检查 relativePath 是否已包含完整的 serverUrl
	if (relativePath.includes(serverUrl)) {
		return relativePath;
	} else {
		return serverUrl + relativePath;
	}
}

export function FullImageUrl(relativePath) {
	const serverUrl = config.baseFullUrl;
	const serverUrl1 = config.baseFullUrl1
	// 检查 relativePath 是否已包含完整的 serverUrl
	if (relativePath.includes(serverUrl)) {
		return relativePath;

	} else if (relativePath.includes(serverUrl1)) {
		return relativePath;
	} else {
		return serverUrl + relativePath;
	}

}

export function isWithinTwoHours(timeRangeStr) {
	// 解析时间字符串（格式：YYYY-MM-DD HH:MM-HH:MM）
	const [dateStr, timeStr] = timeRangeStr.split(' ');
	const [startTime] = timeStr.split('-'); // 只需取开始时间
	const [year, month, day] = dateStr.split('-').map(Number);
	const [startH, startM] = startTime.split(':').map(Number);

	// 创建开始时间的Date对象（月份从0开始）
	const start = new Date(year, month - 1, day, startH, startM);

	// 计算两小时前的时间范围（毫秒）
	const twoHours = 2 * 60 * 60 * 1000;
	const validStart = new Date(start.getTime() - twoHours); // 有效范围起点
	const validEnd = new Date(start.getTime()); // 有效范围终点（开始时间本身）

	// 获取当前时间
	const now = new Date();

	// 判断当前时间是否在有效范围内
	return now >= validStart && now <= validEnd;
}

export function debounce(func, delay = 300) {
	let timer = null;
	return function(...args) {
		clearTimeout(timer);
		timer = setTimeout(() => {
			func.apply(this, args);
		}, delay);
	};
};

//获取二维码参数
export function GetWxMiniProgramUrlParam(url) {
	let theRequest = {};
	if (url.indexOf('#') != -1) {
		const str = url.split('#')[1];
		const strs = str.split('&');
		for (let i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1]);
		}
	} else if (url.indexOf('?') != -1) {
		const str = url.split('?')[1];
		const strs = str.split('&');
		for (let i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1]);
		}
	}
	return theRequest;
}